package com.weiaibenpao.demo.chislim.ui;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;

import com.jaeger.library.StatusBarUtil;
import com.weiaibenpao.demo.chislim.R;
import com.weiaibenpao.demo.chislim.bean.UserBean;
import com.weiaibenpao.demo.chislim.map.activity.PersonalMarathonActivity;
import com.weiaibenpao.demo.chislim.sport.MarathonActivity;
import com.weiaibenpao.demo.chislim.sport.utils.ShareUtils;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

import static com.weiaibenpao.demo.chislim.sport.utils.Constant.AREA_NAME;
import static com.weiaibenpao.demo.chislim.sport.utils.Constant.CITY_CODE;
import static com.weiaibenpao.demo.chislim.sport.utils.Constant.CITY_NAME;
import static com.weiaibenpao.demo.chislim.sport.utils.Constant.MARATHON_DETAILURL;
import static com.weiaibenpao.demo.chislim.sport.utils.Constant.MARATHON_DISTANCE;
import static com.weiaibenpao.demo.chislim.sport.utils.Constant.MARATHON_ID;
import static com.weiaibenpao.demo.chislim.sport.utils.Constant.MARATHON_TITLE;
import static com.weiaibenpao.demo.chislim.sport.utils.Constant.MARATHON_TYPE;
import static com.weiaibenpao.demo.chislim.sport.utils.Constant.MATCH_END_TIME;
import static com.weiaibenpao.demo.chislim.sport.utils.Constant.MATCH_START_TIME;
import static com.weiaibenpao.demo.chislim.sport.utils.Constant.PROVINCE_NAME;
import static com.weiaibenpao.demo.chislim.sport.utils.Constant.SELECT_NAME;
import static com.weiaibenpao.demo.chislim.util.Default.PRODUCT_URL;

public class MarathonWebActivity extends AppCompatActivity {



    WebView myWebView;
    ImageView back;

    String url_record;
    String marathon_detailUrl;
    TextView shareWeb;
    @BindView(R.id.titleTv)
    TextView titleTv;
    private ShareUtils share;

    Map<String, String> map = new HashMap<String, String>();

    class JS {
        private String selectName;

        @JavascriptInterface
        public void go(String p) {

            //todo 前往马拉松跑步
            //p userId=43&marathonId=22&marathonId=21&sportType=232&matchStartTime=522
            subString(p);
            if ("6".equals(map.get("sportType"))) {         //团队马拉松
                selectName = getSelectName(map.get(PROVINCE_NAME), map.get(CITY_NAME), map.get(AREA_NAME));
                Intent intent = new Intent(MarathonWebActivity.this, MarathonActivity.class);
                intent.putExtra(MARATHON_ID, map.get(MARATHON_ID));            //马拉松id
                intent.putExtra(MARATHON_TYPE, map.get(MARATHON_TYPE));              //马拉松类型
                intent.putExtra(MATCH_START_TIME, map.get(MATCH_START_TIME));    //开始时间
                intent.putExtra(MATCH_END_TIME, map.get(MATCH_END_TIME));         //结束时间
                intent.putExtra(MARATHON_DISTANCE, map.get(MARATHON_DISTANCE));              //马拉松跑步里程
                intent.putExtra(CITY_CODE, map.get(CITY_CODE));            //马拉松行政区code
                intent.putExtra(SELECT_NAME, selectName);
                intent.putExtra(MARATHON_TITLE, map.get(MARATHON_TITLE));     //马拉松跑步主题
//                RunningPreferences.getInstance().putString(MARATHON_ID, map.get(MARATHON_ID));
//                RunningPreferences.getInstance().putString(CITY_CODE, map.get(CITY_CODE));
//                RunningPreferences.getInstance().putString(SELECT_NAME, selectName);
//                RunningPreferences.getInstance().putString(MARATHON_DISTANCE, map.get(MARATHON_DISTANCE));
//                RunningPreferences.getInstance().putString(MARATHON_TITLE, map.get(MARATHON_TITLE));
//                RunningPreferences.getInstance().putString(MATCH_END_TIME, map.get(MATCH_END_TIME));
//                RunningPreferences.getInstance().putString(MARATHON_TYPE, map.get(MARATHON_TYPE));
//                RunningPreferences.getInstance().putString(MATCH_START_TIME, map.get(MATCH_START_TIME));
                Log.e("lw", "MARATHON_TITLE: " + map.get(MATCH_END_TIME));
                startActivity(intent);
                finish();
            } else if ("7".equals(map.get("sportType"))) {   //个人马拉松
                Intent intent = new Intent(MarathonWebActivity.this, PersonalMarathonActivity.class);
                intent.putExtra(MARATHON_ID, map.get("marathonId"));//马拉松id
                intent.putExtra(MARATHON_TYPE, map.get("sportType"));//马拉松类型
//                intent.putExtra(MARATHON_START_TIME,map.get("matchStartTime"));//开始时间
                intent.putExtra(MARATHON_DISTANCE, map.get("distance"));    //马拉松跑步里程
                intent.putExtra(MARATHON_TITLE, map.get("marathonTitle"));    //马拉松跑步里程
                startActivity(intent);
                finish();
            }
        }
    }

    private String getSelectName(String provinceName, String cityName, String areaName) {
        String selectName;
        if (TextUtils.isEmpty(cityName)) {
            selectName = provinceName;
        } else if (TextUtils.isEmpty(areaName)) {
            selectName = cityName;
        } else {
            selectName = areaName;
        }
        return selectName;
    }

    /**
     * 解析前端返回的数据
     */
    public void subString(String str) {
        String[] strs = str.split("&");
        Log.e("wlx", "subString: " + str);
        for (int i = 0; i < strs.length; i++) {

            String[] strs_value = strs[i].split("=");
            if (strs_value.length > 1) {
                map.put(strs_value[0], strs_value[1]);
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sportrecord);
        ButterKnife.bind(this);
        StatusBarUtil.setColor(this, getResources().getColor(R.color.ku_bg), 0);
        back = (ImageView) findViewById(R.id.back);

        myWebView = (WebView) findViewById(R.id.myWebView);
        shareWeb = (TextView) findViewById(R.id.shareWeb);
        titleTv.setText(getIntent().getStringExtra(MARATHON_TITLE));
        share = new ShareUtils(this);
       /* url_record = Default.url_li_de + "/" +  "malasong/join.html?" + "userId=" +
                UserBean.getUserBean().userId + "&marathonId=" + getIntent().getStringExtra("marathon_id")
                + "&sportType=" + getIntent().getStringExtra("marathon_type");*/
        marathon_detailUrl = getIntent().getStringExtra(MARATHON_DETAILURL);
        url_record = PRODUCT_URL + marathon_detailUrl + UserBean.getUserBean().userId;
        Log.e("wlx", "url_record: "+url_record );

        myWebView.loadUrl(url_record);
        /**
         * WebSettings用来设置WebView的相关属性
         */
        WebSettings webSettings = myWebView.getSettings();
        //设置WebView支持JavaScript
        webSettings.setJavaScriptEnabled(true);
        webSettings.setAllowContentAccess(true);
        webSettings.setAppCacheEnabled(false);
        webSettings.setBuiltInZoomControls(false);
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        //设置可以访问文件
        webSettings.setAllowFileAccess(true);
        webSettings.setDefaultTextEncodingName("utf-8");
        myWebView.addJavascriptInterface(new JS(), "android");
        //设置支持缩放
        webSettings.setBuiltInZoomControls(true);
        webSettings.setDefaultTextEncodingName("UTF-8");

        initAction();
        /**
         * 判断页面加载过程
         * 当网络加载缓慢,我们可以再页面加载出来之前设置显示进度条
         * setWebChromeClient一般处理加载进度,设置标题,处理js对话框
         */
        myWebView.setWebChromeClient(new WebChromeClient() {
            ProgressDialog dialog;

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);

                if (newProgress == 100) {     //页面加载完成
                    if (dialog != null && dialog.isShowing()) {
                        dialog.dismiss();
                    }
                }else {                     //页面正在加载中
                    if(dialog == null){
                        dialog = new ProgressDialog(MarathonWebActivity.this);
                        dialog.setTitle("正在加载");
                        dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                        dialog.setProgress(newProgress);
                        dialog.show();
                    }else{
                        dialog.setProgress(newProgress);
                    }
                }
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                MarathonWebActivity.this.setTitle(title);           //设置标题
                super.onReceivedTitle(view, title);
            }
        });

        /**
         * WebViewClient帮助webView处理一些页面控制和请求通知
         * 当点击webview控件中的链接时,在这里设置显示在webview中,否则,会在浏览器打开
         */
        myWebView.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view,String url){
                //设置网页在webview控件中打开,false在浏览器中打开
                view.loadUrl(url);
                return true;
            }
        });
        /**
         * 返回
         */
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

        /**
         * 重写onKeyDown方法用于在WebView中点击回退键时,返回url的上一层,
         * 否则会直接跳出WebView
         */
        @Override
        public boolean onKeyDown(int keyCode, KeyEvent event) {
            if((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()){
                myWebView.goBack();    //返回上一页
                return true;
            }else {
                finish();      //某些Android版本不生效        System.exit(0);    //某些Android版本不生效
            }
            return super.onKeyDown(keyCode, event);
        }

        public void initAction(){
            shareWeb.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    //分享
                    shareMyRecord();
                }
            });
        }

    private void shareMyRecord() {
        share.shareLink(url_record,"\"" + getIntent().getStringExtra(MARATHON_TITLE) + "\"，一起来报名吧！","东极圈，跑出不一样的自己；启迈斯为您助跑！");
    }
}
